<template>
  <div class="login-container">
    <!-- 登录成功绿色toast -->
    <div v-if="showToast" class="success-toast">
      {{ toastMsg }}
    </div>
    <!-- 状态栏 -->
    <div class="status-bar">
      <span class="time">12:00</span>
      <div class="status-icons">
        <span class="signal"></span>
        <span class="wifi"></span>
        <span class="battery"></span>
      </div>
    </div>

    <!-- 头部 -->
    <div class="header">
      <div class="close-btn">×</div>

    </div>
    
    <!-- 主要内容 -->
    <div class="content">
      <!-- 手机号显示 -->
      <div class="phone-section">
        <div class="phone-display">
          <div class="phone-numbe1r">{{ maskedPhoneNumber }}</div>
          <div class="switch-icon" @click="showPhoneList">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M7 10L12 15L17 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
        <div class="carrier-info">中国移动提供认证服务</div>
      </div>
      
      <!-- 手机号选择弹窗 -->
      <div v-if="showPhoneSelector" class="phone-selector-overlay" @click="closePhoneSelector">
        <div class="phone-selector" @click.stop>
          <div class="phone-selector-header">
            <h3>选择手机号</h3>
            <div class="close-btn" @click="closePhoneSelector">×</div>
          </div>
          <div class="phone-list">
            <div 
              v-for="phone in phoneList" 
              :key="phone.phoneNumber"
              class="phone-item"
              @click="selectPhone(phone.phoneNumber)"
            >
              <div class="phone-info">
                <div class="phone-number">{{ phone.phoneNumber }}</div>
                <div class="phone-time">注册时间: {{ formatDate(phone.registrationTime) }}</div>
              </div>
              <div class="phone-arrow">></div>
            </div>
            <div v-if="phoneList.length === 0" class="no-phones">
              暂无已注册手机号
            </div>
          </div>
        </div>
      </div>
      
      <!-- 登录按钮 -->
      <div class="login-buttons">
        <button class="primary-btn" @click="handleOneClickLogin" :disabled="!agreed">
          本机手机号一键登录
        </button>
        <button class="secondary-btn" @click="handleOtherLogin">
          其他手机号/账号登录
        </button>
        <div class="auto-register-tip">
          未注册的手机号将自动注册并登录
        </div>
      </div>
      
      <!-- 快速登录 -->
      <div class="quick-login">
        <div class="divider">
          <span class="divider-text">快速登录</span>
        </div>
        <div class="login-methods">
          <div class="method wechat" @click="handleWechatLogin">
            <div class="wechat-icon"></div>
          </div>
          <div class="method face" @click="handleFaceLogin">
            <div class="face-icon"></div>
          </div>
        </div>
      </div>
      
      <!-- 协议同意 -->
      <div class="agreement">
        <label class="checkbox-container">
          <input type="checkbox" v-model="agreed" class="checkbox">
          <span class="checkmark"></span>
        </label>
        <span class="agreement-text">
          我已阅读并同意
          <a href="#" class="link">《中国移动认证服务条款》</a>
          和
          <a href="#" class="link">AI智能医疗辅助系统 用户协议、隐私政策以及儿童个人信息保护政策</a>
        </span>
      </div>
    </div>

    <!-- 底部手势条 -->
    <div class="gesture-bar"></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

export default defineComponent({
  name: 'Login',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const phoneNumber = ref('15999999998')
    const agreed = ref(false)
    const loading = ref(false)
    // toast相关
    const toastMsg = ref('')
    const showToast = ref(false)
    let toastTimer: any = null
    
    // 手机号切换相关
    const showPhoneSelector = ref(false)
    const phoneList = ref<Array<{
      phoneNumber: string
      registrationTime: string
      lastLoginTime: string
    }>>([])
    function showSuccessToast(msg: string) {
      toastMsg.value = msg
      showToast.value = true
      if (toastTimer) clearTimeout(toastTimer)
      toastTimer = setTimeout(() => {
        showToast.value = false
      }, 2000)
    }
  
    // 页面加载时优先显示query手机号
    onMounted(() => {
      if (route.query.phone) {
        const phone = route.query.phone as string
        phoneNumber.value = phone
      }
    })
    // 计算属性：显示脱敏的手机号
    const maskedPhoneNumber = computed(() => {
      return phoneNumber.value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    })

    // 一键登录处理
    const handleOneClickLogin = async () => {
      if (!agreed.value) {
        alert('请先同意服务条款')
        return
      }

      loading.value = true
      try {
        const response = await axios.post('http://localhost:3000/users/login', {
          phoneNumber: phoneNumber.value
        })
        
        if (response.data.success) {
          // 存储登录token和用户信息
          localStorage.setItem('token', response.data.token)
          localStorage.setItem('userInfo', JSON.stringify(response.data.user))
          
          // 显示成功消息
          showSuccessToast(response.data.message)
          
          // 跳转到首页
          setTimeout(() => {
          router.push('/home')
          }, 1200)
        } else {
          alert(response.data.message)
        }
      } catch (error: any) {
        console.error('登录失败:', error)
        if (error.response?.data?.message) {
          alert(error.response.data.message)
        } else {
        alert('登录失败，请稍后重试')
      }
      } finally {
        loading.value = false
      }
    }

    // 其他登录方式
    const handleOtherLogin = () => {
      router.push('/verification-login')
    }

    // 微信登录
    const handleWechatLogin = async () => {
    // 清除 baseURL（或设置为其他值）
    axios.defaults.baseURL = '';
    await axios.get("/api", {
        params: {
            act: "login",
            appid: "3521", //自己去官网申请
            appkey: "a010aaf9582fe1587b08b283a47ca14b", //自己去官网申请
            type: 'wx',
            redirect_uri: "http://127.0.0.1:5173/home", //回调地址,就是你登录成功(账号或扫码)之后进入到的页面
        },               //替换成你自己项目的前端路径就可以 
    }).then((res) => {
        sessionStorage.setItem('longtermToken', 'hhhhnxsm')
        // 保存 code
        window.open(res.data.url, "_self") //打开第三方登录页面
    })
  };


    // 人脸识别登录
    const handleFaceLogin = () => {
      router.push('/face-recognition')
    }

    // 手机号切换相关函数
    const showPhoneList = async () => {
      try {
        const response = await axios.get('http://localhost:3000/users/phone-list')
        if (response.data.success) {
          phoneList.value = response.data.data
          showPhoneSelector.value = true
        } else {
          showSuccessToast('获取手机号列表失败')
        }
      } catch (error: any) {
        showSuccessToast(error.response?.data?.message || '获取手机号列表失败')
      }
    }

    const closePhoneSelector = () => {
      showPhoneSelector.value = false
    }

    const selectPhone = (phone: string) => {
      phoneNumber.value = phone
      closePhoneSelector()
      showSuccessToast(`已切换到手机号: ${phone}`)
    }

    const formatDate = (dateString: string) => {
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    return {
      phoneNumber,
      maskedPhoneNumber,
      agreed,
      loading,
      handleOneClickLogin,
      handleOtherLogin,
      handleWechatLogin,
      handleFaceLogin,
      // toast相关
      toastMsg,
      showToast,
      // 手机号切换相关
      showPhoneSelector,
      phoneList,
      showPhoneList,
      closePhoneSelector,
      selectPhone,
      formatDate
    }
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: #ffffff;
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 44px;
  background: #ffffff;
}

.time {
  font-size: 14px;
  font-weight: 600;
  color: #000;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 4px;
}

.signal, .wifi, .battery {
  width: 20px;
  height: 12px;
  background: #000;
  border-radius: 2px;
}

/* 头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  margin-bottom: 60px;
}

.close-btn {
  font-size: 24px;
  color: #333;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.register-link {
  color: #007AFF;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
}

/* 主要内容 */
.content {
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 手机号部分 */
.phone-section {
  text-align: center;
  margin-bottom: 40px;
}

.phone-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
}

.phone-number {
  font-size: 28px;
  font-weight: 600;
  color: #000;
  letter-spacing: 1px;
}

.carrier-info {
  font-size: 14px;
  color: #8E8E93;
}

/* 登录按钮 */
.login-buttons {
  width: 100%;
  margin-bottom: 40px;
}

.primary-btn {
  width: 100%;
  height: 50px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.primary-btn:hover:not(:disabled) {
  background: #0056CC;
}

.primary-btn:disabled {
  background: #C7C7CC;
  cursor: not-allowed;
}

.secondary-btn {
  width: 100%;
  height: 50px;
  background: #F2F2F7;
  color: #007AFF;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.secondary-btn:hover {
  background: #E5E5EA;
}

.auto-register-tip {
  text-align: center;
  font-size: 12px;
  color: #8E8E93;
  margin-top: 12px;
}

/* 快速登录 */
.quick-login {
  width: 100%;
  margin-bottom: 40px;
}

.divider {
  position: relative;
  text-align: center;
  margin-bottom: 30px;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #E5E5EA;
}

.divider-text {
  background: #ffffff;
  padding: 0 16px;
  color: #8E8E93;
  font-size: 14px;
  position: relative;
  z-index: 1;
}

.login-methods {
  display: flex;
  justify-content: center;
  gap: 40px;
}

.method {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.method:hover {
  transform: scale(1.1);
}

.wechat {
  background: #07C160;
}

.face {
  background: #007AFF;
}

.wechat-icon {
  width: 24px;
  height: 24px;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M8.5,13.5A1.5,1.5 0 0,1 7,12A1.5,1.5 0 0,1 8.5,10.5A1.5,1.5 0 0,1 10,12A1.5,1.5 0 0,1 8.5,13.5M15.5,13.5A1.5,1.5 0 0,1 14,12A1.5,1.5 0 0,1 15.5,10.5A1.5,1.5 0 0,1 17,12A1.5,1.5 0 0,1 15.5,13.5M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z"/></svg>') no-repeat center;
  background-size: contain;
}

.face-icon {
  width: 24px;
  height: 24px;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M9,11A4,4 0 0,1 13,15A4,4 0 0,1 9,19A4,4 0 0,1 5,15A4,4 0 0,1 9,11M9,13A2,2 0 0,0 7,15A2,2 0 0,0 9,17A2,2 0 0,1 9,13M15,11A4,4 0 0,1 19,15A4,4 0 0,1 15,19A4,4 0 0,1 11,15A4,4 0 0,1 15,11M15,13A2,2 0 0,0 13,15A2,2 0 0,0 15,17A2,2 0 0,1 15,13M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4Z"/></svg>') no-repeat center;
  background-size: contain;
}

/* 协议同意 */
.agreement {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 40px;
  padding: 0 10px;
}

.checkbox-container {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  flex-shrink: 0;
  margin-top: 2px;
}

.checkbox {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 20px;
  width: 20px;
  background-color: #fff;
  border: 2px solid #C7C7CC;
  border-radius: 4px;
  transition: all 0.2s;
}

.checkbox:checked ~ .checkmark {
  background-color: #007AFF;
  border-color: #007AFF;
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox:checked ~ .checkmark:after {
  display: block;
}

.checkbox-container .checkmark:after {
  left: 6px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.agreement-text {
  font-size: 12px;
  color: #8E8E93;
  line-height: 1.4;
}

.link {
  color: #007AFF;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

/* 底部手势条 */
.gesture-bar {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 134px;
  height: 5px;
  background: #000;
  border-radius: 3px;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .phone-number {
    font-size: 24px;
  }
  
  .login-methods {
    gap: 30px;
  }
  
  .method {
    width: 45px;
    height: 45px;
  }
}
.success-toast {
  position: fixed;
  left: 50%;
  bottom: 80px;
  transform: translateX(-50%);
  min-width: 180px;
  max-width: 80vw;
  background: #22c55e;
  color: #fff;
  text-align: center;
  padding: 14px 24px;
  border-radius: 18px;
  box-shadow: 0 4px 24px rgba(34,197,94,0.18), 0 1.5px 4px rgba(0,0,0,0.10);
  font-size: 16px;
  letter-spacing: 1px;
  z-index: 9999;
  animation: sms-pop 0.3s;
}
@keyframes sms-pop {
  0% { opacity: 0; transform: translateX(-50%) translateY(30px) scale(0.95);}
  100% { opacity: 1; transform: translateX(-50%) translateY(0) scale(1);}
}

/* 手机号切换相关样式 */
.switch-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  color: #007AFF;
  cursor: pointer;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.switch-icon:hover {
  background-color: rgba(0, 122, 255, 0.1);
}

.phone-selector-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10001;
  animation: fadeIn 0.2s ease-out;
}

.phone-selector {
  background: white;
  border-radius: 12px;
  width: 320px;
  max-width: 90vw;
  max-height: 70vh;
  overflow: hidden;
  animation: slideUp 0.3s ease-out;
}

.phone-selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.phone-selector-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.phone-selector-header .close-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.phone-selector-header .close-btn:hover {
  background-color: #f5f5f5;
}

.phone-list {
  max-height: 400px;
  overflow-y: auto;
}

.phone-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f8f8f8;
  cursor: pointer;
  transition: background-color 0.2s;
}

.phone-item:hover {
  background-color: #f8f9fa;
}

.phone-item:last-child {
  border-bottom: none;
}

.phone-info {
  flex: 1;
}

.phone-info .phone-number {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.phone-time {
  font-size: 12px;
  color: #999;
}

.phone-arrow {
  color: #ccc;
  font-size: 16px;
}

.no-phones {
  padding: 40px 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    opacity: 0; 
    transform: translateY(20px); 
  }
  to { 
    opacity: 1; 
    transform: translateY(0); 
  }
}
</style>